package com.online.onlinestudent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.online.onlinestudent.entity.Course;
import com.online.onlinestudent.entity.Record;
import com.online.onlinestudent.entity.Student;
import com.online.onlinestudent.mapper.CourseMapper;
import com.online.onlinestudent.mapper.RecordMapper;
import com.online.onlinestudent.service.CourseService;
import com.online.onlinestudent.service.RecordService;
import com.online.onlinestudent.service.StudentService;
import com.online.onlinestudent.vo.RecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements RecordService {


    @Autowired
    private CourseService courseService;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private StudentService studentService;

    /**
     * 根据学生id查询学习记录，再根据学习记录里的course_id查询学习过的所有课程
     * @param studentId
     * @return
     */
    @Override
    public List<Course> getRecordsByStudentId(Long studentId) {
        // 根据学生ID查询所有Record记录
        QueryWrapper<Record> queryRecord = new QueryWrapper<>();
        queryRecord.eq("student_id", studentId);
        List<Record> records = this.list(queryRecord);

        // 提取所有course_id
        List<Long> courseIds = records.stream()
                .map(Record::getCourseId)
                .collect(Collectors.toList());

        // 根据course_id查询所有课程
        QueryWrapper<Course> queryCourse = new QueryWrapper<>();
        queryCourse.in("id", courseIds);
        return courseService.list(queryCourse);
    }

    @Override
    public List<Record> getRecordsByStudentIDAndCourseId(Long studentId,Long courseId) {
        QueryWrapper<Record> queryRecord = new QueryWrapper<>();
        queryRecord.eq("course_id", courseId);
        queryRecord.eq("student_id", studentId);
        List<Record> records = this.list(queryRecord);
//        records.forEach(record -> {
//            if(record.getProgress()<100)
//            {
//                record.setProgress(record.getProgress()+5);
//            }
//            LocalDateTime now = LocalDateTime.now();
//            record.setUpdatedAt(now);
//            this.updateById(record);
//        });
        return records;
    }

    @Override
    public boolean saveOrUpdateRecord(Long student_id,Long course_id) {
        if (student_id == null || course_id == null) {
            return false; // 如果 studentId 或 courseId 为空，直接返回 false
        }
        // 根据 studentId 和 courseId 查询是否已存在记录
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", student_id)
                .eq("course_id", course_id);

        Record existingRecord = this.getOne(queryWrapper);

        if (existingRecord == null) {
            // 如果不存在，则新建一个 Record 对象并插入
            Record record = new Record();
            record.setStudentId(student_id);
            record.setCourseId(course_id);
            record.setProgress(5.0); // 设置初始进度为 0
            record.setCreatedAt(LocalDateTime.now()); // 设置创建时间
            record.setUpdatedAt(LocalDateTime.now()); // 设置更新时间
            return this.save(record);
        } else {
            // 如果存在，则更新记录（例如增加进度）
            if (existingRecord.getProgress() < 100) {
                existingRecord.setProgress(existingRecord.getProgress() + 5); // 增加进度
            }
            existingRecord.setUpdatedAt(LocalDateTime.now()); // 设置更新时间
            return this.updateById(existingRecord);
        }
    }
    @Override
    public List<Record> getAllRecordByCourse(List<Course> courses) {
        List<Record> records = new ArrayList<>();
        for (Course course : courses) {
            QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("course_id", course.getId());
            List<Record> list = baseMapper.selectList(queryWrapper);
            records.addAll(list);
        }

        return records;
    }

    @Override
    public List<RecordVO> getAllRecordsWithCourse() {
        // 假设你使用 MyBatis Plus 进行查询
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        List<Record> records = this.list(queryWrapper);

        List<RecordVO> recordVOs = new ArrayList<>();
        for (Record record : records) {
            RecordVO recordVO = new RecordVO();
            recordVO.setStudentId(record.getStudentId());
            recordVO.setCourseId(record.getCourseId());
            recordVO.setStartTime(record.getStartTime());
            recordVO.setEndTime(record.getEndTime());
            recordVO.setProgress(record.getProgress());
            recordVO.setRecordStatus(record.getStatus());
            recordVO.setCreatedAt(record.getCreatedAt());
            recordVO.setUpdatedAt(record.getUpdatedAt());

            // 获取 Course 信息
            Course course = courseService.getById(record.getCourseId());
            if (course != null) {
                recordVO.setTitle(course.getTitle());
                recordVO.setDescription(course.getDescription());
                recordVO.setCourseIntroduction(course.getCourseIntroduction());
                recordVO.setVideoUrl(course.getVideoUrl());
                recordVO.setImageUrl(course.getImageUrl());
                recordVO.setCategoryId(course.getCategoryId());
                recordVO.setTeacherId(course.getTeacherId());
                recordVO.setCourseStatus(course.getStatus());
            }
            Student student = studentService.getById(record.getStudentId());
            if(student != null)
            {
                recordVO.setStudentName(student.getUsername());
            }
            recordVOs.add(recordVO);
        }

        return recordVOs;
    }


}
